package org.huangjie.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.huangjie.util.Ipv6Utils;
import org.huangjie.ddns.DDns;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Huang Jie
 * @date 2024/05/18
 */
@Slf4j
@Component
@AllArgsConstructor
public class Tasks implements ApplicationRunner {
    private static final ConcurrentHashMap<String,String> MAP = new ConcurrentHashMap<>();
    private static final String IPV6_KEY = "ipv6";
    private DDns<String> dDns;

    @Scheduled(cron ="0 0/1 * * * ?")
    public void sync() {
        List<String> localIpv6s = Ipv6Utils.getLocalIpv6s();
        if (CollectionUtil.isEmpty(localIpv6s)){
            log.info("ipv6未开启");
            return;
        }

        log.info("ipv6-print-start:"+DateUtil.now());
        localIpv6s.forEach(log::info);
        log.info("ipv6-print-end:"+DateUtil.now());

        String ipv6 = localIpv6s.get(1);
        String oldIpv6 = MAP.get(IPV6_KEY);

        log.info("target-ipv6:"+ipv6);
        log.info("old-ipv6:"+oldIpv6);

        // 如果ipv6未变化,则不推送
        if (ipv6.equals(oldIpv6)) {
            log.info("ipv6未变化");
            return;
        }

        log.info("push ipv6:{}",ipv6);
        dDns.update(ipv6);
        MAP.put(IPV6_KEY,ipv6);
    }

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void syncEveryHour(){
        // 不管ipv6是否变化,每小时都更新ddns
        String ipv6 = MAP.get(IPV6_KEY);
        if (ipv6 == null) {
            log.warn("ipv6为空");
            return;
        }
        dDns.update(ipv6);
        log.info("每日更新ddns成功");
    }

    /**
     * 启动时，同步一次
     * */
    @Override
    public void run(ApplicationArguments args) {
        sync();
    }
}
